<!--  -->
<template>
  <div class="app">
    <!-- 头部功能栏 -->
    <div class="float-left j-b-flex mb-30">
      <div class="d-flex">
        <button type="button" class="el-button el-button--primary" @click="routerGoTo('MemberCreate')">
          <span>添加学员</span>
        </button>
        <button type="button" class="el-button ml-15 el-button--primary" @click="routerGoTo('MemberImport')">
          <span>批量导入</span></button
        ><button type="button" class="el-button ml-15 el-button--primary" @click="sendMessage('batch')">
          <span>批量发消息</span></button
        ><button type="button" class="el-button ml-15 el-button--primary" @click="selectUserAlert('dialogFormVisible1')">
          <span>批量修改</span>
        </button>
      </div>
      <div class="d-flex">
        <div>
          <div class="w-150px el-input">
            <input
              type="text"
              autocomplete="off"
              placeholder="学员关键字"
              v-model="searchCon"
              class="el-input__inner"
            />
          </div>
        </div>
        <div class="ml-10">
          <button type="button" class="el-button el-button--default" @click="clearSearch">
            <span>清空</span></button
          ><button type="button" class="el-button el-button--primary" @click="filterSearch">
            <span>筛选</span>
          </button>
        </div>
        <div class="drawerMore d-flex ml-10" @click="moreFilter">
          <img
            src=""
          /><span>更多</span>
        </div>
      </div>
    </div>

    <div class="float-left mb-30 check-num">已选择{{ multipleSelection.length }}项</div>
    <!-- 表格 -->
    <el-table
      ref="multipleTable"
      :data="userData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :default-sort="{ prop: 'id', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="55" align="center"> </el-table-column>
      <el-table-column prop="id" label="学员ID" width="100" sortable="custom"> </el-table-column>
      <el-table-column prop="name" label="学员" width="210">
        <template slot-scope="scope">
          <div class="block" style="width: auto; display: flex; align-items: center">
            <el-avatar
              :size="40"
              :src="scope.row.avatar"
              fit="cover"
              style="margin-right: 10px; background: transparent"
            ></el-avatar>
            <div>{{ scope.row.name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="注册时间"
        width="210"
        sortable="custom"
      ></el-table-column>
      <el-table-column prop="mobile" label="手机号" width="180"> </el-table-column>
      <el-table-column prop="roleName" label="VIP会员" width="150"> </el-table-column>
      <el-table-column prop="credit1" label="积分" width="120" sortable="custom"></el-table-column>
      <el-table-column prop="tags" label="标签" width="200">
        <template slot-scope="scope">
          <el-tag
            v-for="(value, index) in scope.row.tags"
            :key="value.user_id + '' + index"
            v-text="value.name"
            style="margin-left: 5px"
          ></el-tag>
          <!-- {{scope.row.tags}} -->
        </template>
      </el-table-column>
      <el-table-column prop="user_remarks" label="备注" width="auto">
        <template slot-scope="scope">
          <div v-html="scope.row.user_remarks"></div>
          <!-- <p v-text=""></p> -->
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row.id)" type="text" size="middle">查看</el-button>

          <el-dropdown @command="sendMessage">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="scope.row.id">发消息</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 底部分页栏 -->
    <div class="pageBar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 发送消息框 -->
    <el-dialog title="发消息" :visible.sync="dialogFormVisible" width="25%" >
      <el-input
        type="textarea"
        placeholder="请输入内容"
        v-model="MessageContent"
        maxlength="500"
        show-word-limit
        resize="none"
        rows="5"
      >
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSendMessage">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 更多筛选---抽屉 -->
    <el-drawer title="更多筛选" :visible.sync="drawer" size="20%" :show-close="false">
      <div>
        <el-input v-model="searchCon" placeholder="学员列表关键字"></el-input>
        <div class="mb-30"></div>

        <el-select v-model="selectVip" placeholder="VIP会员">
          <el-option
            v-for="(item, index) in roles"
            :key="item.name + '' + index"
            :label="item.name"
            :value="item.name"
            :data-name="item.name"
          >
          </el-option>
        </el-select>
        <div class="mb-30"></div>

        <el-select v-model="selectTag" placeholder="学员标签">
          <el-option
            v-for="(item, index) in tags"
            :key="item.name + '' + index"
            :label="item.name"
            :value="item.name"
            :data-name="item.name"
          >
          </el-option>
        </el-select>
        <div class="mb-30"></div>
        <el-date-picker
          v-model="dateValue"
          type="daterange"
          range-separator="至"
          start-placeholder="注册开始日期"
          end-placeholder="注册结束日期"
          :picker-options="dataOptionsObj"
        >
        </el-date-picker>
        <div class="mb-30"></div>
        <div class="ml-10 flex-spaceBetween">
          <button type="button" class="el-button el-button--default" @click="clearSearch">
            <span>清空</span></button
          ><button type="button" class="el-button el-button--primary" @click="filterSearch">
            <span>筛选</span>
          </button>
        </div>
      </div>
    </el-drawer>

    <!-- 批量修改 -->
    <el-dialog title="批量修改" :visible.sync="dialogFormVisible1" width="25%" >
      
        <!-- <el-button @click="dialogFormVisible1 = false">取 消</el-button> -->
          <el-select v-model="batchModifyValue.modifyType" placeholder="请选择">
    <el-option key="选项一" label="修改vip"  value="1"> </el-option>
    <el-option key="选项二" label="修改标签"  value="2"> </el-option>
    <el-option key="选项三" label="是否禁止登录"  value="3"> </el-option>
    
  </el-select>
  <div class="mb-30"></div>
  <template v-if="batchModifyValue.modifyType == '1'">
    <div class="flex-spaceCenter">
      <div style="width:35%;margin-right:5%" class="flex-alignCenter flex-spaceEnd">选择vip</div>
       <div style="width:60%" class="flex-spaceEnd">
        <el-select v-model="batchModifyValue.selectVip" placeholder="请选择">
          <el-option
            v-for="(item, index) in roles"
            :key="item.name + '' + index"
            :label="item.name"
            :value="item.id"
            :data-name="item.name"
          >
          </el-option>
        </el-select>
       </div>
    </div>
    <div class="mb-30"></div>
     <div class="flex-spaceCenter">
    
        <div style="width:35%;margin-right:5%" class="flex-alignCenter flex-spaceEnd">vip过期时间</div>
       <div style="width:60%" class="flex-spaceEnd">
         <el-date-picker
           v-model="batchModifyValue.selectDate"
           type="datetime"
            placeholder="选择日期时间">
        </el-date-picker>
        
       </div>
    </div>
  </template>
  <template v-if="batchModifyValue.modifyType == '2'">
    <div class="flex-spaceCenter">
      <div style="width:35%;margin-right:5%" class="flex-alignCenter flex-spaceEnd">选择标签</div>
       <div style="width:60%" class="flex-spaceEnd">
        <el-select v-model="batchModifyValue.selectTag" multiple  placeholder="请选择">
          <el-option
            v-for="(item, index) in tags"
            :key="item.name + '' + index"
            :label="item.name"
            :value="item.id"
            :data-name="item.name"
          >
          </el-option>
        </el-select>
       </div>
    </div>
  </template>
  <template v-if="batchModifyValue.modifyType == '3'">
    <div class="flex-spaceCenter">
      <div style="width:35%;margin-right:5%" class="flex-spaceCenter">是否禁止登录</div>
       <div style="width:60%" class="flex-spacesStart">
        <el-switch
          v-model="batchModifyValue.isBanLogin"
          active-color="#409eff"
          inactive-color="#dcdfe6">
        </el-switch>
       </div>
    </div>
  </template>
        
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="batchModify" >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import instance from "@/api/instance";
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      dialogFormVisible: false, //发送消息框的显示隐藏
      dialogFormVisible1: false, //批量修改框的显示隐藏
      total: 0, //数据总条数
      currentPage: 1, //分页栏当前第1页
      userData: [], //表格渲染的数据
      multipleSelection: [], //多选框数组
      page: 1, //分页获取
      pageSize: 10, //分页获取
      order: "desc", //排序方式
      sort: "id", //排序项
      MessageContent: "", //发送消息的内容
      sendMessageId: "", //要发送消息的用户id
      batchSendMsgFlag:false,
      searchCon: "", //搜索框的内容
      drawer: false, // 更多筛选抽屉显示隐藏
      roles: "", //会员种类
      selectVip: "", //选中的会员类型
      dateValue: "", //筛选日期
      tags: [], //标签种类
      selectTag: "", //选择的标签种类
      //未来日期禁用
      dataOptionsObj: {
        disabledDate: function (date) {
          let currentTime = new Date();
          return date > currentTime;
          // return console.log(date);
        },
      },
      batchModifyValue : {
        modifyType: '',
        selectVip:'',
        selectDate:'',
        selectTag:'',
        isBanLogin:false,
      },   //批量修改选择选项
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    selectUserAlert(val){
      if(this.multipleSelection.length == 0){
         this.$message('请选择用户')
          return
      }
      switch (val) {
        case 'dialogFormVisible1':
          this.dialogFormVisible1 = true
          break;
        default:
          break;
      }
    },
    //更多筛选
    SendmoreFilter() {},
    //更多筛选--打开抽屉
    moreFilter() {
      this.drawer = true;
    },
    //清空搜索框
    clearSearch() {
      if (
        !this.searchCon &&
        !this.dateValue &&
        !this.selectVip &&
        !this.selectTag &&
        !this.searchCon
      ) {
        return this.$message("已经是空的啦");
      }
      this.dateValue = "";
      this.selectVip = "";
      this.selectTag = "";
      this.searchCon = "";
      // this.sendRequest();
    },
    //筛选搜索
    async filterSearch() {
      let _dateValue1 = "";
      let _dateValue2 = "";
      let _selectVip = "";
      let _selectTag = "";
      let _searchCon = "";
      _selectTag = this.tags
        .map((item) => {
          if (item.name === this.selectTag) {
            return item.id;
          } else {
            return "";
          }
        })
        .join("");
      _selectVip = this.roles
        .map((item) => {
          if (item.name === this.selectVip) {
            return item.id;
          } else {
            return "";
          }
        })
        .join("");
      // let _dateValue = this.dateValue.length == 0 ? '' : '&created_at[]=' + '['+(this.dateValue = [this.dateValue[0].toISOString(),this.dateValue[1].toISOString()]) +']';
      _dateValue1 =
        this.dateValue.length == 0 ? "" : "&created_at[]=" + this.dateValue[0].toISOString();
      _dateValue2 =
        this.dateValue.length == 0 ? "" : "&created_at[]=" + this.dateValue[1].toISOString();
      _selectVip = this.selectVip == "" ? "" : "&role_id=" + this.selectVip;
      _selectTag = this.selectTag == "" ? "" : "&tag_id=" + this.selectTag;
      _searchCon = this.searchCon == "" ? "" : "&keywords=" + this.searchCon;
      await this.$request
        .get(
          `/member?page=${this.page}&size=${this.pageSize}&sort=${this.sort}&order=${this.order}${_selectTag}${_selectVip}${_searchCon}${_dateValue1}${_dateValue2}`
        )
        .then((res) => {
          // console.log(res);
          let resData = res.data;
          let userInfo = res.data.data;
          this.total = userInfo.total;
          // console.log(userInfo);
          this.userData = [];
          for (let i = 0; i < userInfo.data.length; i++) {
            this.userData.push({
              id: userInfo.data[i].id,
              name: userInfo.data[i].nick_name,
              avatar: userInfo.data[i].avatar,
              created_at: this.changeTime(new Date(userInfo.data[i].created_at)),
              mobile: userInfo.data[i].mobile,
              roleName:
                userInfo.data[i].role == (null || undefined) ? "" : userInfo.data[i].role.name,
              credit1: userInfo.data[i].credit1,
              tags: userInfo.data[i].tags,
              user_remarks:
                resData.user_remarks[userInfo.data[i].id] == undefined
                  ? ""
                  : resData.user_remarks[userInfo.data[i].id].remark,
            });
          }
        });
      this.dateValue = "";
      this.selectVip = "";
      this.selectTag = "";
      this.searchCon = "";
    },
    //批量修改
   async batchModify(){
      
      // console.log(this.multipleSelection);
      let user_ids = this.multipleSelection.map(item=>{
        return item.id
      })
      
      if(this.batchModifyValue.modifyType == '1'){
        if(this.batchModifyValue.selectVip == ""){
          this.$message('请选择vip')
          return
        }
        if(this.batchModifyValue.selectDate == ""){
          this.$message('请选择过期时间')
          return
        }
       await this.$request.put('/member/field/multi',{
          user_ids,
          role_expired_at:this.batchModifyValue.selectDate,
          field: "role_id",
          value:this.batchModifyValue.selectVip,

        }).then(res=>{
            // console.log(res);
            this.dialogFormVisible1 = false;
            this.batchModifyValue.modifyType='';
            this.batchModifyValue.selectVip='';
            this.batchModifyValue.selectDate='';
            
        })
      }
      if(this.batchModifyValue.modifyType == '2'){
        
        if(this.batchModifyValue.selectTag == "" || this.batchModifyValue.selectTag.length==0){
          this.$message('请选择标签')
          return
        }
        
       await this.$request.put('/member/field/multi',{
          user_ids,
          // role_expired_at:this.batchModifyValue.selectDate,
          field: "tag",
          tag_ids:this.batchModifyValue.selectTag,
          // value:this.batchModifyValue.selectVip,

        }).then(res=>{
            // console.log(res);
            this.dialogFormVisible1 = false;
            this.batchModifyValue.modifyType='';
            this.batchModifyValue.selectTag='';
            
        })
      }
      if(this.batchModifyValue.modifyType == '3'){
        // console.log(this.batchModifyValue.isBanLogin);
        // console.log(this.batchModifyValue.isBanLogin);
        await this.$request.put('/member/field/multi',{
            user_ids,
            field: "is_lock",
            // value:parseInt(this.batchModifyValue.isBanLogin),
            value:this.batchModifyValue.isBanLogin,
            

          }).then(res=>{
              // console.log(res);
              this.dialogFormVisible1 = false;
              this.batchModifyValue.modifyType='';
              this.batchModifyValue.isBanLogin=false;
              
          })
      }
      this.sendRequest()
      
    },
    //打开发送消息框
    sendMessage(val) {
      // console.log(id);
      if(val == "batch"){
        if(this.multipleSelection.length == 0) return this.$message('请选择学员')
        this.batchSendMsgFlag = true
      }
      else{
        this.sendMessageId = val;
      }
      // console.log(val);
     
      this.dialogFormVisible = true;
    },
    //点击确认发送消息
    confirmSendMessage() {
      // console.log("dialogFormVisible = false");
      // console.log(this.MessageContent);
      if (!this.MessageContent) {
        this.$message("请输入内容");
        return;
      } else if (this.MessageContent.length > 1) {
        if(this.batchSendMsgFlag){
          // console.log(1);
          this.$request
          .post(`/member/message/multi`, {
            message: this.MessageContent,
            user_ids:this.multipleSelection,
          })
          .then((res) => {
            // console.log(res);
            this.$message("发送成功");
          })
          .catch((err) => {
            this.$message("发送失败");
          });
          this.batchSendMsgFlag = false;
        }
        else{
          this.$request
          .post(`/member/${this.sendMessageId}/message`, {
            message: this.MessageContent,
          })
          .then((res) => {
            // console.log(res);
            this.$message("发送成功");
          })
          .catch((err) => {
            this.$message("发送失败");
          });
        }
      }

      this.MessageContent = "";
      this.dialogFormVisible = false;
    },
    //数据条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.sendRequest();
    },
    //数据当前页
    handleCurrentChange(val) {
      this.page = val;
      this.sendRequest();
      // console.log(`当前页: ${val}`);
    },
    handleClick(id) {
      console.log(id);
      this.$router.push({
        name:'MemberDetail',
        params:{
          id
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // console.log(this.multipleSelection);
    },
    //时间格式转换
    changeTime(time) {
      let Y, M, D, H, m, s;
      Y = time.getFullYear();
      M = time.getMonth() + 1 < 0 ? "0" + time.getMonth() + 1 : time.getMonth() + 1;
      D = time.getDate() < 0 ? "0" + time.getDate() : time.getDate();
      H = time.getHours() < 0 ? "0" + time.getHours() : time.getHours();
      m = time.getMinutes() < 0 ? "0" + time.getMinutes() : time.getMinutes();
      s = time.getSeconds() < 0 ? "0" + time.getSeconds() : time.getSeconds();
      return Y + "-" + M + "-" + D + " " + H + ":" + m + ":" + s;
    },
    //发送请求
    async sendRequest() {
      await this.$request
        .get(
          `/member?page=${this.page}&size=${this.pageSize}&sort=${this.sort}&order=${this.order}`
        )
        .then((res) => {
          // console.log(JSON.parse(JSON.stringify(res)));
          // let obj = {}
          let resData = res.data;
          let userInfo = res.data.data;
          this.total = userInfo.total;
          this.roles = res.data.roles;
          this.tags = res.data.tags;

          // console.log(this.roles,"roles");
          // console.log(resData);
          // console.log(resData.data.to);
          // console.log(userInfo);
          this.userData = [];
          for (let i = 0; i < userInfo.data.length; i++) {
            // for (let i = 0; i < resData.data.to; i++) {
            this.userData.push({
              id: userInfo.data[i].id,
              name: userInfo.data[i].nick_name,
              avatar: userInfo.data[i].avatar,
              created_at: this.changeTime(new Date(userInfo.data[i].created_at)),
              mobile: userInfo.data[i].mobile,
              roleName:
                userInfo.data[i].role == (null || undefined) ? "" : userInfo.data[i].role.name,
              credit1: userInfo.data[i].credit1,
              tags: userInfo.data[i].tags,
              user_remarks:
                resData.user_remarks[userInfo.data[i].id] == undefined
                  ? ""
                  : resData.user_remarks[userInfo.data[i].id].remark,
            });
          }
        });
    },
    //排序
    sortChange(val) {
      // console.log(val);
      this.sort = val.prop;
      if (val.order == "descending") {
        this.order = "desc";
      } else if (val.order == "ascending") {
        this.order = "asc";
      } else {
        return;
      }
      this.sendRequest();
    },
    routerGoTo(val){
      
        this.$router.push({
        name:val,
        
      })
      
      
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  async created() {
    this.sendRequest();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.app {
  width: 100%;
  height: auto;
  float: left;
  background-color: #fff;
  box-sizing: border-box;
  padding: 30px;
  border-radius: 15px;
  margin-bottom: 90px;
  box-shadow: 0 2px 4px 0 hsl(0deg 0% 40% / 5%);
  min-width: 1180px;
  height: 1000px;
  /deep/.el-table th {
    background: rgb(241, 242, 249);
    color: #333;
  }
  .flex-alignCenter {
    // width: 100%;
    display: flex;
    // justify-content: space-between;
    align-items: center;
  }
  .flex-spacesStart {
    width: 100%;
    display: flex;
    justify-content: start;
  }
  .flex-spaceEnd {
    width: 100%;
    display: flex;
    justify-content: end;
  }
  .flex-spaceBetween {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
  .flex-spaceCenter {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .float-left {
    width: 100%;
    height: auto;
    float: left;
  }

  .check-num {
    font-size: 14px;
    color: #409eff;
  }
  .mb-30 {
    margin-bottom: 30px;
  }
  .j-b-flex {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .d-flex {
      display: flex;
      align-items: center;
      .el-button {
        font-weight: 400;
      }
      .ml-15 {
        margin-left: 15px;
      }
      div {
        .w-150px {
          width: 150px;
        }
      }

      div.ml-10 {
        margin-left: 10px;
      }

      div.drawerMore.d-flex.ml-10 {
        img {
          width: 14px;
          height: 14px;
          margin-right: 5px;
        }

        span {
          height: 14px;
          font-size: 14px;
          font-weight: 400;
          color: #666;
          line-height: 14px;
          cursor: pointer;
        }
      }
    }
  }
  .pageBar {
    text-align: center;
    margin-top: 30px;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
  }
  .el-icon-arrow-down {
    font-size: 14px;
  }
  /deep/.el-drawer__header {
    width: 100%;
    height: 16px;
    font-size: 16px;
    font-weight: 400;
    color: #333;
    line-height: 16px;
    margin-bottom: 30px;
  }
  /deep/.el-drawer {
    padding: 15px;
  }
  /deep/.el-select {
    width: 100%;
  }
  /deep/.el-range-editor.el-input__inner {
    width: 100%;
    justify-content: space-between;
  }
  .el-range-separator {
    width: 7%;
  }
  /deep/.el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: 100%;
  }
}
</style>
